package org.jeecg.modules.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.DeviceConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.device.entity.DevDeviceInfo;
import org.jeecg.modules.device.mapper.DevDeviceInfoMapper;
import org.jeecg.modules.drive.service.IDriveCtwingService;
import org.jeecg.modules.system.entity.SysThirdAppConfig;
import org.jeecg.modules.system.mapper.SysThirdAppConfigMapper;
import org.jeecg.modules.system.service.ISysThirdAppConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @Description: 第三方配置表
 * @Author: jeecg-boot
 * @Date:   2023-02-03
 * @Version: V1.0
 */
@Service
@Slf4j
public class SysThirdAppConfigServiceImpl extends ServiceImpl<SysThirdAppConfigMapper, SysThirdAppConfig> implements ISysThirdAppConfigService {

    @Autowired
    private SysThirdAppConfigMapper configMapper;
    @Autowired
    private DevDeviceInfoMapper devDeviceInfoMapper;
    @Autowired
    private IDriveCtwingService driveCtwingService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<SysThirdAppConfig> getThirdConfigListByThirdType(int tenantId) {
        return configMapper.getThirdConfigListByThirdType(tenantId);
    }

    @Override
    public SysThirdAppConfig getThirdConfigByThirdType(Integer tenantId, String thirdType) {
        return configMapper.getThirdConfigByThirdType(tenantId,thirdType);
    }

    @Override
    public List<SysThirdAppConfig> getThirdAppConfigByClientId(String clientId) {
        LambdaQueryWrapper<SysThirdAppConfig> query = new LambdaQueryWrapper<>();
        query.eq(SysThirdAppConfig::getClientId,clientId);
        List<SysThirdAppConfig> sysThirdAppConfigs = configMapper.selectList(query);
        return sysThirdAppConfigs;
    }

    @Override
    public void thirdSyn(SysThirdAppConfig thirdAppConfig) {

        SysThirdAppConfig config = configMapper.selectById(thirdAppConfig.getId());

        // 当前租户
        String tenantId = oConvertUtils.getString(TenantContext.getTenant(), "0");

        try{
            /**1. 缓存产品信息*/
            JSONObject rsObj = driveCtwingService.sdkNbQueryProductList(config.getClientId(), config.getClientSecret(), "", 1, 30);
            Integer code = rsObj.getInteger("code");
            if(code == 0){

                // 清空物联网-产品列表
                redisUtil.removeAll(DeviceConstant.DEVICE_AIOT_PRODUCT_SET+"::"+tenantId);
                // 清空物联网-产品信息
                redisUtil.removeAll(DeviceConstant.DEVICE_AIOT_PRODUCT_DATA+"::"+tenantId);

                // 返回结果
                JSONObject resultObj = rsObj.getJSONObject("result");
                if(null != resultObj){
                    // 明细列表
                    JSONArray productLs = resultObj.getJSONArray("list");

                    if(null != productLs && productLs.size()>0){
                        for (Object productObj : productLs) {
                            JSONObject prodItem = (JSONObject)productObj;
                            String productId = prodItem.getString("productId");
                            redisUtil.sSet(DeviceConstant.DEVICE_AIOT_PRODUCT_SET+"::"+tenantId,productId);
                            redisUtil.hset(DeviceConstant.DEVICE_AIOT_PRODUCT_DATA+"::"+tenantId,productId,prodItem);
                        }
                    }
                }
            }

            /**2. 缓存设备信息*/
            // 获取所有产品Set
            Set<Object> productSet = redisUtil.sGet(DeviceConstant.DEVICE_AIOT_PRODUCT_SET+"::"+tenantId);
            for (Object productObj : productSet) {
                String productId = (String)productObj;
                JSONObject deviceRsObj = driveCtwingService.sdkNbQueryDeviceList(config.getClientId(), config.getClientSecret(),
                        config.getAgentAppSecret(), productId, "", 1, 30);
                Integer deviceCode = deviceRsObj.getInteger("code");
                if(deviceCode == 0){
                    // 清空物联网-设备列表
                    redisUtil.removeAll(DeviceConstant.DEVICE_AIOT_DEVICE_SET+"::"+tenantId);
                    // 清空物联网-设备信息
                    redisUtil.removeAll(DeviceConstant.DEVICE_AIOT_DEVICE_DATA+"::"+tenantId);

                    // 返回结果
                    JSONObject resultObj = deviceRsObj.getJSONObject("result");
                    if(null != resultObj){
                        // 明细列表
                        JSONArray deviceLs = resultObj.getJSONArray("list");
                        if(null != deviceLs && deviceLs.size()>0){
                            for (Object deviceObj : deviceLs) {
                                JSONObject item = (JSONObject)deviceObj;
                                String deviceId = item.getString("deviceId");

                                // 封装本地保存
                                this.savePageDeviceNode(item);

                                redisUtil.sSet(DeviceConstant.DEVICE_AIOT_DEVICE_SET+"::"+tenantId,deviceId);
                                redisUtil.hset(DeviceConstant.DEVICE_AIOT_DEVICE_DATA+"::"+tenantId,deviceId,item);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){

        }
    }

    /**
     * 保存封装设备信息
     * @param item
     * @return
     */
    private void savePageDeviceNode(JSONObject item) {
        String deviceCode = null != item.get("deviceSn") ? item.getString("deviceSn") : item.getString("deviceId");
        DevDeviceInfo devDeviceInfo = devDeviceInfoMapper.queryByCode(deviceCode);
        if(null == devDeviceInfo){
            devDeviceInfo = new DevDeviceInfo();
        }
        devDeviceInfo.setDeviceName(item.getString("deviceName"));
        devDeviceInfo.setProductId(item.getString("productId"));
        devDeviceInfo.setDeviceCode(deviceCode);
        devDeviceInfo.setDeviceId(item.getString("deviceId"));
        devDeviceInfo.setDeviceStatus(item.getString("deviceStatus")); // 激活使用状态
        devDeviceInfo.setStatus(item.getString("netStatus"));   // 在线状态
        devDeviceInfo.setOnlineAt(DateUtils.getDate(item.getLong("onlineAt"))); // 最后上线时间
        devDeviceInfo.setImei(item.getString("imei"));
        devDeviceInfo.setDriveType(3);

        if(null != devDeviceInfo.getId()){
            devDeviceInfoMapper.updateById(devDeviceInfo);
        }else{
            devDeviceInfoMapper.insert(devDeviceInfo);
        }
    }
}
